<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="7" :offset="0">
                    <el-form-item label="公司名称">
                        <el-input v-model="searchForm.name" placeholder="公司名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="13">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
                <el-col :span="2">
                    <el-button type="primary" text @click="showAddWin">未找到客户，点击新增</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 表格数据 
        @row-click 当某一行被点击时会触发该事件
        @selection-change 当选择项发生变化时会触发该事件
        @select 当用户手动勾选数据行的 Checkbox 时触发的事件
        -->
        <el-table :data="tableData" 
            stripe 
            style="width: 100%" 
            v-loading="tableDataLoading" 
            :border="true"
            @select = "handlerSelect"
            @row-click="handleSelectionChange"
            highlight-current-row 
            ref="multipleTableRef" 
            :row-key="row => row.id">

            <el-table-column v-if="props.showSelection" type="selection" :reserve-selection="true" align="center" width="55" />

            <el-table-column label="公司名称" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.name }}
                </template>
            </el-table-column>

            <el-table-column label="公司注册地址" align="center" show-overflow-tooltip>
                <template #default="{ row }">
                    {{ row.address }}
                </template>
            </el-table-column>

            <el-table-column label="公司成立时间" align="center">
                <template #default="{ row }">
                    {{ row.establishmentTime }}
                </template>
            </el-table-column>

            <el-table-column label="公司电话" align="center">
                <template #default="{ row }">
                    {{ row.phone }}
                </template>
            </el-table-column>

            <el-table-column label="公司邮箱" align="center">
                <template #default="{ row }">
                    {{ row.email }}
                </template>
            </el-table-column>

            <el-table-column label="创建人" align="center">
                <template #default="{ row }">
                    {{ row.createUsername }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" title="新增客户" @submit="handleSubmit">
            <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
                <el-form-item label="公司名称" prop="name">
                <el-input v-model="form.name" placeholder="公司名称"></el-input>
                </el-form-item>

                <el-form-item label="注册地址" prop="address">
                <el-input v-model="form.address" placeholder="公司注册地址"></el-input>
                </el-form-item>

                <el-form-item label="成立时间" prop="establishmentTime">
                    <el-date-picker
                    v-model="form.establishmentTime"
                    type="date"
                    placeholder="选择日期"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="公司电话" prop="phone">
                <el-input v-model="form.phone" placeholder="公司电话"></el-input>
                </el-form-item>

                <el-form-item label="公司邮箱" prop="email">
                <el-input v-model="form.email" placeholder="公司邮箱"></el-input>
                </el-form-item>
            </el-form>
        </FormDrawer>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, defineProps, nextTick } from 'vue'
import FormDrawer from "~/components/FormDrawer.vue"
import { dateFormatter } from '~/utils/common.js'
import { toast } from "~/composables/util"
const tableData = ref([]) // 列表数据
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)
const selectCheckList = ref([])
const multipleTableRef = ref()
import { getCompanyList,addCompany } from "~/api/userApi"

// props
const props = defineProps({
    //已选择的公司id
    selectedCompanyId: null,
    //是否展示checkbox勾选框
    showSelection: false
})

// 查询条件
const searchForm = reactive({
    name: "",
    page: currentPage.value,
    size: limit.value,
})

// 触发回显
const toggleSelection = async (rows) => {
    //console.log('已选中公司id:', props.selectedCompanyId)
    await nextTick(() => {
        if (rows) {
            rows.forEach((row) => {
                //console.log('row: ', row)
                if (row.id == props.selectedCompanyId) {
                    //console.log('row 触发勾选')
                    multipleTableRef.value.toggleRowSelection(row, true) // 默认勾选
                } else {
                    multipleTableRef.value.toggleRowSelection(row, false) // 不选中
                }
            })
        } else {
            multipleTableRef.value.clearSelection()
        }
    })
}

// 生命周期
onMounted(async () => {
    //加载表格数据
    await getData()
})

//获取列表数据
async function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }
    tableDataLoading.value = true
    searchForm.page = currentPage.value
    getCompanyList(searchForm)
        .then(res => {
            if (res) {
                tableData.value = res.records
                total.value = res.total
                toggleSelection(tableData.value)
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            tableDataLoading.value = false
        })
}

// 重置搜索框
const resetSearchForm = () => {
    searchForm.name = ""
    getData()
}


//当用户手动勾选数据行的 Checkbox 时触发的事件
function handlerSelect(selection, row) {
    // console.log("handlerSelect row===>",JSON.stringify(row))
    selectCheckList.value = [row]
    //清空所有勾选
    multipleTableRef.value.clearSelection()
    //选中当前行
    multipleTableRef.value.toggleRowSelection(row, true);
    //触发对外方法
    getCheckedCompany()
}

//当选择项发生变化时会触发该事件
function handleSelectionChange(row) {
    // console.log("handleSelectionChange===>",JSON.stringify(row))
    selectCheckList.value = [row]
    //清空所有勾选
    multipleTableRef.value.clearSelection()
    //选中当前行
    multipleTableRef.value.toggleRowSelection(row, true);
    //触发对外方法
    getCheckedCompany()
}

// 对外暴露方法
const emit = defineEmits([
    'getCheckedCompany',
])

const getCheckedCompany = () => {
    //console.log("getCheckedCompany===>",JSON.stringify(selectCheckList.value))
    const selectData = selectCheckList.value
    //console.log("selectData===>",JSON.stringify(selectData))
    let returnParams = selectData.length == 1 ? selectData[0] : null
    emit("getCheckedCompany", returnParams)
}

//表单部分---------------
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    name: "",
    address: "",
    description: "",
    phone: "",
    email: "",
    establishmentTime: null
})

const showAddWin = () => {
    if (formRef.value) formRef.value.resetFields()
    //打开弹窗
    formDrawerRef.value.open()
}

//执行表单校验
const rules = {
    name: [
        { required: true, message: '公司名称不能为空', trigger: 'change' }
    ],
    description: [
        { required: true, message: '公司描述不能为空', trigger: 'change' }
    ]
}

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return
        //loading
        formDrawerRef.value.showLoading()
        const fun = addCompany(form)
        fun.then(res => {
            toast("新增成功")
            formDrawerRef.value.close()
            //重新加载table
            getData(1)
        })
        .finally(() => {
            //close loading
            formDrawerRef.value.hideLoading()
        })
    })
}
//表单部分---------------

</script>

<style>
.el-table__header-wrapper .el-checkbox {
    display: none
}
</style>
